package com.audi.activity;

import java.util.ArrayList;
import java.util.List;

import lib.relay.DevListInfo;
import lib.relay.RelayInterface;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.audi.R;
import com.audi.BaseActivity;
import com.audi.adapter.HomeBoxSettingAdapter;
import com.audi.dto.HomeBoxItem;
import com.audi.view.AudiDialog;
import com.audi.box.server.TCPClient;
public class HomeBoxSettings extends BaseActivity {
	private ArrayList<HomeBoxItem> mlistHomeboxItem;
	private HomeBoxSettingAdapter mHomeBoxSettingAdapter;
	private ListView listView;
	private AudiDialog mDialogRootAccess;
	private ImageView mHomeBoxSettingDrawer;
	private String nameVersion = "";
	private ProgressDialog mDlgProgress = null;
	private boolean bIsLogoutWhenExit = false;
	private TCPClient mTcpClient;	
	String ip;
	int port;
	String TAGlistener ="listener";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_box_setting_activity);
		initActionBar();
		setListenerBoxSetting();
		RelayInterface.m_onAuthListener = this;
		initView();
		initData();
		initListener();
	}

	private void initView() {
		listView = (ListView) findViewById(R.id.list_item_setting);
		// tempId = R.layout.action_bar_main;

	}

	private void initData() {
		mlistHomeboxItem = new ArrayList<HomeBoxItem>();
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_rootaccess), "", true));
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_internet), "Wifi 1", true));
		try {
			PackageInfo pInfo = getPackageManager().getPackageInfo(
					getPackageName(), 0);
			nameVersion = pInfo.versionName;
		} catch (Exception e) {
		}
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_software),
				"ver. " + nameVersion, false));
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_number), String
						.valueOf(HomeControlActivity.numberDevice), false));
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_disconnect), "", true));
		mlistHomeboxItem.add(new HomeBoxItem(
				getString(R.string.box_setting_reset), "", true));
		mHomeBoxSettingAdapter = new HomeBoxSettingAdapter(this,
				mlistHomeboxItem);
		listView.setAdapter(mHomeBoxSettingAdapter);
	}

	public void initListener() {
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentHomeBoxSetting,
					View viewHomeBoxSetting, int position, long i) {
				switch (position) {
				case 0:
					onLoginRootAccess();
					break;
				case 1:
					Intent myIntent = new Intent(HomeBoxSettings.this,
							HomeboxWifiSetting.class);
					startActivityForResult(myIntent, 1);
					break;
				case 2:

					break;
				case 4:
					bIsLogoutWhenExit = true;
					CreateProgressDialog(getString(R.string.box_setting_disconnect_content));
					RelayInterface.RelayDeInit();
					break;

				default:
					break;
				}
			}
		});
	}

	private void CreateWarningDialog(String strMessage) {
		AlertDialog.Builder m_Builder = new AlertDialog.Builder(this);
		m_Builder.setTitle(getString(R.string.box_setting_disconnect_title));
		m_Builder.setMessage(strMessage);
		m_Builder.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
		m_Builder.create().show();
	}

	private void CreateProgressDialog(String strMessage) {
		mDlgProgress = new ProgressDialog(this);
		mDlgProgress.setTitle(getString(R.string.box_setting_disconnect_title));
		mDlgProgress.setMessage(strMessage);
		mDlgProgress.setIndeterminate(true);
		mDlgProgress.setCancelable(true);
		mDlgProgress.show();
	}

	private void DestroyProgressDialog() {
		if (mDlgProgress != null)
			mDlgProgress.dismiss();
	}

	private void onLoginRootAccess() {
		mDialogRootAccess = new AudiDialog(this);
		mDialogRootAccess.setLayout(R.layout.dialog_login_root_access);
		final EditText txtRootID = (EditText) mDialogRootAccess
				.findViewById(R.id.edt_root_access_id);
		//pass
		final EditText txtPassWord = (EditText) mDialogRootAccess
				.findViewById(R.id.edt_root_access_pass);
		txtRootID.setHint(getString(R.string.box_setting_rootaccess_hint));
		txtPassWord.setHint(getString(R.string.port));
		Button btnLogInRootAccessCancel = (Button) mDialogRootAccess
				.findViewById(R.id.btn_rename_device_dialog_skip);
		Button btnLogInRootAccessOk = (Button) mDialogRootAccess
				.findViewById(R.id.btn_rename_device_dialog_ok);
		btnLogInRootAccessCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mDialogRootAccess.dismiss();
			}
		});
		btnLogInRootAccessOk.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!(txtRootID.equals(null) || txtRootID.equals(null))) {
					Intent intent = new Intent(v.getContext(),
							RootAccessActivity.class);
					v.getContext().startActivity(intent);
					//click to reconnect
//					ip = txtRootID.getText().toString();
//					 port = Integer.parseInt(txtPassWord.getText().toString());
//					 new connectTask().execute("");
					
					mDialogRootAccess.dismiss();
				} else
					Toast.makeText(HomeBoxSettings.this,
							"Check RootID or Password", Toast.LENGTH_LONG)
							.show();
			}

		});
		mDialogRootAccess.show();
	}

	protected void initActionBar() {
		mHomeBoxSettingDrawer = (ImageView) findViewById(R.id.btn_action_menu_more);
		mHomeBoxSettingDrawer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
					mDrawerLayout.openDrawer(mDrawerList);
				} else {
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			}
		});

	}

	@Override
	public void onRefreshData() {

	}

	public String GetLogTag() {
		String strTag = "[Home Box]";
		return strTag;
	}

	@Override
	public void GetAuthFinished(boolean bValue) {

	}

	@Override
	public void ListProfileFinished(List<DevListInfo> relay_list) {

	}

	@Override
	public void LogoutFinished(final boolean bValue) {
		runOnUiThread(new Runnable() {
			public void run() {
				DestroyProgressDialog();
				Intent intent = new Intent(HomeBoxSettings.this,
						SigninActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	public void CBInit(boolean bValue) {

	}

	@Override
	public void CBMakeCall(boolean bValue) {

	}

	@Override
	public void CBHangUp(boolean bValue) {

	}

	@Override
	public void CBDeInit(boolean bValue) {
		if (bValue == true) {
			Log.d(GetLogTag(), "[MainActivity.java] DeInit Relay successfully.");
			RelayInterface.LogoutRelayS();
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					DestroyProgressDialog();
					Log.d(GetLogTag(),
							"[MainActivity.java] Failed to DeInit Relay.");
					CreateWarningDialog("Failed to DeInit Relay");
				}
			});

		}
	}

	@Override
	public void CBClientSocket(String CBString) {

	}

	@Override
	public void ThreadRun(int iID) {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == 1) {
			Bundle mBuddle = data.getExtras();
			String wifi = mBuddle.getString("wifi");
			mlistHomeboxItem.set(1, new HomeBoxItem(
					getString(R.string.box_setting_internet), wifi, true));
			mHomeBoxSettingAdapter.swapItems(mlistHomeboxItem);
		}
	}
	public void setListenerBoxSetting() {
		txtHomeBoxSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
					mDrawerLayout.openDrawer(mDrawerList);
				} else {
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			}
		});
	}

	public class connectTask extends AsyncTask<String,String,TCPClient> {
		 
        @Override
        protected TCPClient doInBackground(String... message) {
 
            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                }
            });
            mTcpClient.run(ip,port);
 
            return null;
        }
 
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
 
            //in the arrayList we add the messaged received from server
            Log.d(TAGlistener,"listener");
           Toast.makeText(HomeBoxSettings.this, "Receiver", Toast.LENGTH_SHORT);
            // notify the adapter that the data set has changed. This means that new message received
            // from server was added to the list
//            mAdapter.notifyDataSetChanged();
        }
    }
}

